<template>
  <el-card shadow="always">
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-row :span="18">
          <el-col :span="4">
            <el-form-item label="设置年份">
              <el-date-picker
                  ref="yearRef"
                  v-model="currentYear"
                  type="year"
                  placeholder="选择年份"
                  @change="changeYear"
              />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="日历类型">
              <baseCombox url="/pricing/durationController/queryTradeCalendar.action" clearable
                          valueField="CAL_CODE" labelField="CAL_NAME" disabled
                          @change="handleQuery" placeholder="日历类型" v-model="queryParams.calCode">
                          </baseCombox>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item>
              <el-button type="primary" icon="Search" size="small" 
              v-hasPermi="['trade:tradecalendar:setall']"
              @click="handleSetYearCalDay">设置交易日</el-button>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="1.5">
            <el-form-item>
              <el-button type="primary" icon="Search" size="small" @click="handleClearYearCalDay">清空交易日</el-button>
            </el-form-item>
          </el-col> -->

        </el-row>
      </el-form>
      <el-divider></el-divider>


      <div class="yearPanel">
        <el-icon :size="30" class="leftArrow pointer" @click.stop="prev">
          <arrow-left/>
        </el-icon>
        <el-icon :size="30" class="rightArrow pointer" @click.stop="next">
          <arrow-right/>
        </el-icon>


        <el-card class="xCalendarBox" v-for="(mounth,index) in mounths" :key="index">
          <xCalendar
              ref="xCalendar"
              :value="[currentYear.getFullYear(),mounth,1]"
              :events="events"
              @select="updateCalendar">
          </xCalendar>
        </el-card>

      </div>

    </div>
  </el-card>
</template>



<!--交易日历-->
<script setup name="TradeCalendar">
import {queryTradeCalendarDates,updateTradeCalendarDates,updateTradeCalendarDatesByYear,
insertTCalendarDatesIfNotExist,insertTCalendarDatesIfNotExistByYear} from "@/api/trade/tradecalendar";
import { ref } from "@vue/reactivity";
import { ElMessageBox } from 'element-plus'
const {proxy} = getCurrentInstance();
const tradeCalendarList = ref([]);

//当前年份
const currentYear = ref(new Date());

//每年日历开始日期，从一月开始
const currentDate = ref(new Date(new Date().getFullYear(),0,1));

const data = reactive({
  queryParams: {
    calCode: 'CHINA_EX',
    calYear: new Date().getFullYear()
  },
  mounths: [
    1,2,3,4,5,6,7,8,9,10,11,12
  ],
  events: {
  }
});

const {queryParams,attrs,mounths,events} = toRefs(data);


//联动日历,currentDate是日历开始的年月数
function changeYear() {
  queryParams.value.calYear = currentYear.value.getFullYear();
  getTradeCalendarDatesList();
}

function prev(){
  currentYear.value.setFullYear(currentYear.value.getFullYear() -1);
  queryParams.value.calYear = currentYear.value.getFullYear();
  getTradeCalendarDatesList();
}

function next(){
  currentYear.value.setFullYear(currentYear.value.getFullYear() +1);
  queryParams.value.calYear = currentYear.value.getFullYear();
  getTradeCalendarDatesList();
}

/** 日历类型切换查询操作 */
function handleQuery() {
  queryParams.value.calYear = currentYear.value.getFullYear();
  getTradeCalendarDatesList();
}


/** 查询交易日历配置列表 */
function getTradeCalendarDatesList() {
  queryTradeCalendarDates(queryParams.value).then(response => {
    tradeCalendarList.value = response;
     handleCalDay();
  });
}



function handleCalDay() {
  var calDays = [];
  //不知道为什么先得置空
  events.value = {}
  tradeCalendarList.value.forEach(element => {
    if(element.CAL_FLAG === 1){
      calDays.push(new Date(element.CAL_DAY))
      //得到的CAL_DAY有0，日历的event不能有0
      events.value[deleteZero(element.CAL_DAY)] = '1';
    }
  });

}


//更新日历配置
function updateCalendar(value){
  var params = {};
  params.calDay = value[0] + '-' + value[1] + '-' + value[2];
  var tempDate = params.calDay;

  if(events.value[deleteZero(tempDate)] === '1'){
    params.calFlag = 0;
  }else{
    params.calFlag = 1;
  }

  params.calCode = queryParams.value.calCode;
  insertTCalendarDatesIfNotExist(params).then(response => {
    if (response.success) {
      if(events.value[deleteZero(tempDate)] === '1'){
          proxy.$modal.msgSuccess("取消交易日成功");
      }else{
          proxy.$modal.msgSuccess("设置交易日成功");
      }
      getTradeCalendarDatesList();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  })
}


function handleSetYearCalDay() {
    ElMessageBox.confirm(
    '该操作会将当年工作日设置为交易日，确认继续？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      var params = {};
      params.calCode = queryParams.value.calCode;
      params.calDays = getWeekDaysForYear(currentYear.value.getFullYear());
      params.calFlag = 1;
      insertTCalendarDatesIfNotExistByYear(params).then(response => {
      if (response.success) {
        proxy.$modal.msgSuccess("设置交易日成功")
        getTradeCalendarDatesList();
      } else {
        proxy.$modal.msgError(response.msg);
      }
    });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消设置',
      })
    })
}


function handleClearYearCalDay() {
    ElMessageBox.confirm(
    '该操作会将当年交易日清空，确认继续？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        var params = {};
        params.calCode = queryParams.value.calCode;
        params.calYear = currentYear.value.getFullYear();
        params.calFlag = 0;
      params.calCode = queryParams.value.calCode;
      updateTradeCalendarDatesByYear(params).then(response => {
        if (response.success) {
          proxy.$modal.msgSuccess("清空交易日成功");
          getTradeCalendarDatesList();
        } else {
          proxy.$modal.msgError(response.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消设置',
      })
    })

}

//获取一年的周一到周五
function getWeekDaysForYear(year) {
  const isLeap = year % 4 === 0;
  const numberOfDays = isLeap ? 366 : 365;
  let currentDate = new Date(Date.UTC(year, 0, 0, 0, 0, 0, 0));

  const weekDays = [];

  for(let i = 1; i <= numberOfDays; i++) {
    currentDate = new Date(currentDate.getTime() + 24 * 3600 * 1000);
    if (currentDate.getDay() === 0 || currentDate.getDay() === 6) {
      continue;
    }
    weekDays.push(currentDate.toISOString().split('T')[0]);
  }
  return weekDays;
}

// 日期去掉0
function deleteZero(str) {
    let strArray = str.split('-');
    strArray = strArray.map(function(val) {
        if (val[0] == '0') {
            return val = val.slice(1);
        }else{
            return val;
        }
    })
    return strArray.join('-');
}

getTradeCalendarDatesList();

</script>
<style lang="scss" scoped>

.el-row {
  margin-bottom:10px;
}
.xCalendarBox {
  //width: 24%;
  aspect-ratio: 1 / 1;
  display: -webkit-inline-box;
  margin: 2px;
}

.yearPanel{
  position:relative;
  padding-left: 50px;
}

.leftArrow {
  position: absolute;
  top: 5px;
  left: 0px;
}

.rightArrow {
  position: absolute;
  top: 5px;
  right: 5px;
}

.pointer{
   cursor: pointer;
}
.el-card__body {
  padding: 0px 0px 0px 0px !important;
}

</style>
